package com.dikang.keer.product.execption;

import com.dikang.common.utils.R;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:KeerlExceptionControllerAdvice
 * Package:com.dikang.keer.product.execption
 * Description:
 *
 * @date:2021/11/3 20:31
 * @author:caojunjie
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.dikang.keer.product.controller")
public class KeerlExceptionControllerAdvice {
    @ExceptionHandler(value = Exception.class) // 也可以返回ModelAndView
    public R handleValidException(MethodArgumentNotValidException exception){

        Map<String,String> map=new HashMap<>();
        // 获取数据校验的错误结果
        BindingResult bindingResult = exception.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            String message = fieldError.getDefaultMessage();
            String field = fieldError.getField();
            map.put(field,message);
        });

        log.error("数据校验出现问题{},异常类型{}",exception.getMessage(),exception.getClass());

        return R.error(400,"数据校验出现问题").put("data",map);
    }

    // 默认异常处理
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("未知异常{},异常类型{}",throwable.getMessage(),throwable.getClass());
        return R.error(400,"数据校验出现问题");
    }
   /* // 空指针异常
    @ExceptionHandler(value = NullPointerException .class)
    public R notTimeException(NullPointerException  e){
        log.error("未知异常{},异常类型{}",e.getMessage(),e.getClass());
        return R.error(400,"传递参数不能为空");
    }*/
}
